<?php

namespace App\Http\Controllers\Shop\Product;

use App\Http\Controllers\ShopController;
use App\Models\Business\Business as BusinessModel;
use App\Models\Business\Address as AddressModel;
use App\Models\Product\Cart as CartModel;
use App\Models\Product\Order\Order as OrderModel;
use App\Models\Product\Order\Product as OrderProductModel;
use App\Models\Product\Product as ProductModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class OrderController extends ShopController
{
    public function confirm()
    {
        $params = request()->input();

        $business = request()->get('business');

        $cartids = isset($params['cartids']) ? explode(',',$params['cartids']) : [];

        $CartData = CartModel::with(['product'])->whereIN('id',$cartids)->get();

        if(!$CartData)
        {
            return $this->error('找不到购物车');
        }

        $address = AddressModel::find($params['addrid']);

        // 订单的总金额
        $total = 0;

        foreach($CartData as $item)
        {
            $stock = bcsub($item['product']['stock'],$item['nums']);

            if($stock < 0)
            {
                return $this->error("{$item['product']['name']}库存不足");
            }

            $total += $item['total'];
        }

        /* 
            新增订单
            新增订单商品
            更新商品库存
            删除购物车
        */

        // 开启事务
        DB::beginTransaction();
        // dd($params);
        $OrderData = [
            'code' => build_code('BU'),
            'busid' => $business['id'],
            'businessaddrid' => $address['id'],
            'amount' => $total,
            'remark' => trim($params['content']) ?? null,
            'status' => (String)0
        ];
        
        $validate = [
            [
                'busid' => 'required', //必填
                'businessaddrid' => 'required', //必填
                'code' => 'required|unique:order',
                'status' => 'in:0,1,2,3,4',  //给字段设置范围
                'amount' => 'required'
            ],
            [
                'busid.required'  => '用户信息未知',
                'businessaddrid.required'  => '收货地址未知',
                'code.required' => '订单号必填',
                'code.unique' => '订单号已存在，请重新输入',
                'amount.required' => '订单号金额未知',
            ]
        ];

        $validator = Validator::make($OrderData,...$validate);

        if($validator->fails())
        {
            return $this->error($validator->errors()->first());
        }

        $OrderStatus = OrderModel::create($OrderData);

        // 订单商品数据
        $OrderProductData = [];
        // dd($CartData);
        foreach($CartData as $item)
        {
            $OrderProductData[] = [
                'orderid' => $OrderStatus->id,
                'proid' => $item['proid'],
                'pronum' => $item['nums'],
                'price' => $item['price'],
                'total' => $item['total'],
                'busid' => $item['busid'],
            ];
        }

        $OrderProductValidate = [
            [
                'orderid' => 'required', //必填
                'proid' => 'required', //必填
                'pronum' => 'required|gt:0', //必填
                'price' => 'required|gt:0', //必填
                'total' => 'required|gt:0', //必填
                'busid' => 'required', //必填
            ],
            [
                'orderid.required'    => '订单ID未知',
                'proid.required'    => '商品ID未知',
                'busid.required'    => '用户ID未知',
                'pronum.required'    => '请填写商品数量',
                'price.required'    => '请填写商品的单价',
                'total.required'    => '请填写商品的总价',
                'pronum.gt'    => '商品数量大于0',
                'price.gt'    => '商品的单价大于0',
                'total.gt'    => '商品的总价大于0',
            ]
        ];

        foreach($OrderProductData as $item)
        {
            $OrderProductValidator = Validator::make($item,...$OrderProductValidate);

            if($OrderProductValidator->fails())
            {
                return $this->error($OrderProductValidator->errors()->first());
            }
        }

        $OrderProductStatus = OrderProductModel::insert($OrderProductData);
    
        // 更新商品库存
        $ProductData = [];

        foreach($CartData as $item)
        {
            // ProductModel::where(['id' => $item['proid']])->update(['stock' => bcsub($item['product']['stock'],$item['nums'])]);
            $ProductData[] = [
                'id' => $item['proid'],
                'stock' => bcsub($item['product']['stock'],$item['nums'])
            ];
        }

        // 第一个参数：需要更新数据 第二个参数 检查该列的值是否存在 第三个参数 需要修改的列
        $ProductStatus = ProductModel::upsert($ProductData,['id'],['stock']);

        // 补充订单商品验证器

    
        $CartStatus = CartModel::destroy($cartids);

        // if($OrderStatus === false || $OrderProductStatus === false || $CartStatus === false)
        if($OrderStatus === false || $OrderProductStatus === false || $ProductStatus === false || $CartStatus === false)
        {
            DB::rollBack();
            return $this->error('下单失败');
        }else{
            DB::commit();
            return $this->success('下单成功');
        }
    }

    public function index()
    {
        $busid = request('busid',0);
        $page = request('page',1);
        $limit = request('limit',10);
        $status = request('status','');

        $start = ($page - 1) * $limit;

        $where = [
            'busid' => $busid
        ];
        
        if($status !== '' && $status !== -1)
        {
            $where['status'] = (string)$status;
            // dd($where['status']);
        }elseif($status === -1)
        {
            $where[] = ['status','<','0'];
        }
        // dd($where);
        $OrderData = OrderModel::with('order_product.products')->where($where)->offset($start)->limit($limit)->orderBy('order.createtime','desc')->get();
        // dd($OrderData);
        // $OrderCount = OrderModel::with('order_product')->where($where)->count();
        $count=count($OrderData);
        if($status==='6'){
            
            $OrderData = OrderModel::with('order_product.products')->where('status','3')->orWhere('status','4')->offset($start)->limit($limit)->orderBy('order.createtime','desc')->get();
            // $OrderCount = OrderModel::with('order_product')->where('status','3')->orWhere('status','4')->count();
            $count=count($OrderData);
            if($count > 0){
            foreach($OrderData as $key=>$value)
            {
                if($value['busid']!==$busid){
                    unset($OrderData[$key]);
                    $count--;
                }     
            }   
            }
            
            
        }

        if($count > 0)
        {
            return $this->success('查询成功',['count' => $count,'list' => $OrderData]);
        }else{
            return $this->error('暂无订单',[]);
        }
    }

    public function pay()
    {
        $id = request('id',0);
        $busid = request('busid',0);
        $money = request('money',0);
        // dd($money);
        $result = BusinessModel::where('id',$busid)->update(['money'=>$money]);
        $status = OrderModel::where('id',$id)->update(['status'=>'2']);

        if($result&&$status)
        {
            return $this->success('支付成功');
            
        }else{
            return $this->error('支付失败');
        }
    }

    public function detail()
    {
        $id = request('id',0);
        $businessaddrid = request('businessaddrid',0);
        // $busid = request('busid',0);
        // dd($businessaddrid);
        $OrderData = OrderModel::with('order_product.products')->where('id',$id)->orderBy('order.createtime','desc')->first();
        // $OrderCount = OrderModel::with('order_product')->where('id',$id)->count();
        $AddressData = AddressModel::where('id',$businessaddrid)->first();
        if($businessaddrid!==0){
        if($OrderData&&$AddressData)
        {
            return $this->success('查询成功',['list' => $OrderData,'address'=>$AddressData]);
        }else{
            return $this->error('暂无订单',[]);
        }
    }else{
        if($OrderData)
        {
            return $this->success('查询成功',['list' => $OrderData]);
        }else{
            return $this->error('暂无订单',[]);
        }
    }
        // dd($id);
        // return 1111;
    }


}
